<template>
  <view class="chat-page">
    <!-- 聊天内容区域 -->
    <view class="chat-content">
      <view class="chat-time">{{ currentTime }}</view>
      <view
        v-for="(msg, idx) in messages"
        :key="idx"
        :class="['chat-item', msg.from === userId ? 'me' : 'other']"
      >
        <image
          class="avatar"
          :src="msg.from === userId ? '/static/logo.png' : '/static/logo.png'"
          mode="aspectFill"
        />
        <view class="bubble-wrap">
          <view class="bubble" v-if="!msg.isImage">
            {{ msg.content }}
            <view class="bubble-triangle"></view>
          </view>
          <view class="bubble" v-else>
            <image
              class="chat-image"
              :src="msg.image"
              mode="widthFix"
              @click="previewImage(msg.image)"
            />
            <view class="bubble-triangle"></view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部输入区域 -->
    <view class="chat-input-bar">
      <input
        v-model="inputMsg"
        class="chat-input"
        placeholder="请输入消息"
        confirm-type="send"
        @confirm="sendMsg"
      />
      <view class="emoji-btn" @click="toggleEmoji">
        <image
          src="/static/images/icon/emoji.png"
          mode="aspectFit"
          style="width: 40rpx; height: 40rpx"
        />
      </view>
      <view class="add-btn" v-if="!inputMsg" @click="handleAddClick">
        <image
          src="/static/images/icon/plus.png"
          mode="aspectFit"
          style="width: 40rpx; height: 40rpx"
        />
      </view>
      <button
        v-else
        class="send-btn"
        :class="{ 'slide-in': inputMsg }"
        @click="sendMsg"
      >
        发送
      </button>
    </view>
    <view class="action-sheet" v-if="showActionSheet">
      <view class="action-container">
        <view class="action-option" @click="chooseImage('album')">
          <image
            class="action-icon"
            src="/static/images/icon/album.png"
            mode="aspectFit"
          />
          <text class="action-text">相册</text>
        </view>
        <view class="action-option" @click="chooseImage('camera')">
          <image
            class="action-icon"
            src="/static/images/icon/camera.png"
            mode="aspectFit"
          />
          <text class="action-text">拍照</text>
        </view>
      </view>
      <view class="action-cancel" @click="showActionSheet = false">
        <text>取消</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import dayjs from "dayjs";
import { getHistory, sendMessage } from "../../api/customerService";

const userId = ref(uni.getStorageSync("userId"));

if (!userId.value) {
  uni.showToast({ title: "请先登录", icon: "none" });
  setTimeout(() => uni.navigateTo({ url: "/src/pages/login/login" }), 800);
}
if (!uni.getStorageSync("userId")) {
  uni.setStorageSync("userId", "test_user_001");
}

const messages = ref<any[]>([]);
const fetchHistory = async () => {
  if (!userId.value) return;
  const res = await getHistory(userId.value);
  if (res.code === 0) {
    messages.value = res.data;
  }
};
const showActionSheet = ref(false);

const handleAddClick = () => {
  showActionSheet.value = true;
};

const chooseImage = (type: "album" | "camera") => {
  uni.chooseImage({
    sourceType: [type === "album" ? "album" : "camera"],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      messages.value.push({
        from: userId.value,
        isImage: true,
        image: tempFilePaths[0],
      });
    },
    complete: () => {
      showActionSheet.value = false;
    },
  });
};
const currentTime = ref("");
const getCurrentTime = () => {
  const now = dayjs();
  const hour = now.hour();

  let period = "上午";
  if (hour >= 12 && hour < 18) {
    period = "下午";
  } else if (hour >= 18) {
    period = "晚上";
  }

  currentTime.value = `${period} ${now.format("HH:mm")}`;
};
const inputMsg = ref("");
const sendMsg = async () => {
  if (!inputMsg.value.trim()) return;
  const res = await sendMessage({
    from: userId.value,
    to: "customer_service",
    content: inputMsg.value,
  });
  if (res.code === 0) {
    messages.value.push(res.data);
    inputMsg.value = "";
  }
};
const toggleEmoji = () => {
  uni.showToast({ title: "表情功能暂未开发", icon: "none" });
};

const previewImage = (url: string) => {
  uni.previewImage({
    current: url,
    urls: [url],
  });
};
// 添加定时轮询
let pollTimer: any = null;
onMounted(() => {
  fetchHistory();
  getCurrentTime();
  // 每3秒轮询一次消息
  pollTimer = setInterval(fetchHistory, 3000);
});
onUnmounted(() => {
  if (pollTimer) {
    clearInterval(pollTimer);
  }
});
</script>
<style scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #eeeeee;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 0 20rpx 0;
  background: #eeeeee;
}

.chat-time {
  text-align: center;
  color: #999;
  font-size: 24rpx;
  margin: 20rpx 0;
}

.chat-item {
  display: flex;
  align-items: flex-start;
  margin: 30rpx 24rpx;
}

.chat-item.other {
  flex-direction: row;
}

.chat-item.me {
  flex-direction: row-reverse;
}

.avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 8rpx;
  background: #ccc;
}

.bubble-wrap {
  max-width: 60%;
  display: flex;
  flex-direction: column;
}

.bubble {
  position: relative;
  padding: 20rpx 28rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  margin: 0 30rpx;
  word-break: break-all;
}

.bubble .chat-image {
  max-width: 200rpx;
  max-height: 300rpx;
  border-radius: 16rpx;
  display: block;
}

.chat-item.other .bubble {
  background: #fff;
  color: #333;
}

.chat-item.me .bubble {
  background: #a2ec65;
  color: #333;
}

.bubble-triangle {
  position: absolute;
  width: 0;
  height: 0;
  border-style: solid;
}

.chat-item.other .bubble-triangle {
  left: -16rpx;
  top: 20rpx;
  border-width: 12rpx 16rpx 12rpx 0;
  border-color: transparent #fff transparent transparent;
}

.chat-item.me .bubble-triangle {
  right: -16rpx;
  top: 20rpx;
  border-width: 12rpx 0 12rpx 16rpx;
  border-color: transparent transparent transparent #a2ec65;
}

.chat-input-bar {
  display: flex;
  align-items: center;
  padding: 16rpx;
  background: #fff;
  border-top: 1px solid #eee;
  position: relative;
  overflow: hidden;
}

.emoji-btn,
.add-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
}

.chat-input {
  flex: 1;
  height: 64rpx;
  border: none;
  border-radius: 32rpx;
  background: #f5f5f5;
  padding: 0 24rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.send-btn {
  background: #a2ec65;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  padding: 0 20rpx;
  height: 64rpx;
  font-size: 28rpx;
  line-height: 64rpx;
  margin-left: 16rpx;

  animation: slideIn 0.3s ease forwards;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.action-sheet {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #f7f7f7;
  padding: 20rpx 0;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 999;
}

.action-container {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 0;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

.action-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 150rpx;
}

.action-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 20rpx;
}

.action-text {
  font-size: 28rpx;
  color: #333;
}

.action-cancel {
  margin-top: 20rpx;
  background: #fff;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #333;
  border-radius: 20rpx;
}
</style>
